package com.scau.dunka.service;

import com.easyFramework.annotation.Service;
import com.scau.dunka.bean.Article;
import com.scau.dunka.bean.Category;
import com.scau.dunka.dao.ArticleDao;
import com.scau.dunka.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public  class ArticleService {
    private ArticleDao articleDao;
    //系统时间，用于记录写博文或修改博文
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    /*
        通过博文id获取博文
     */
    public Article getArticleById(long id){
        SqlSession session = MybatisUtil.openSession();
        articleDao = session.getMapper(ArticleDao.class);
        Article article = articleDao.getArticleById(id);
        article.setCategory(articleDao.getCategoryById(article.getCategoryId()).getDisplayName());
        return article;
    }

    /*
        获得前10篇博文
     */
    public List<Article> getFirst10Article() {
        SqlSession session = MybatisUtil.openSession();
        articleDao = session.getMapper(ArticleDao.class);
        return articleDao.getFirst10Article();
    }
    /*
        获取所有分类名
     */
    public List<Category> getCategories() {
        SqlSession session = MybatisUtil.openSession();
        articleDao = session.getMapper(ArticleDao.class);
        return articleDao.getCategories();
    }

    /*
        新增或更新文章
     */
    public void insertOrUpdateBlog(Article article) {
        SqlSession session = MybatisUtil.openSession();
        articleDao = session.getMapper(ArticleDao.class);
        article.setSummary(article.getContent().substring(0, Math.min(article.getContent().length(), 20)));
        articleDao.insertOrUpdateArticleById(article);
        session.commit();
        session.close();
    }
    /*
        通过博文ID删除博文
     */
    public void deleteArticleById(Long id) {
        SqlSession session = MybatisUtil.openSession();
        articleDao = session.getMapper(ArticleDao.class);
        articleDao.deleteArticleById(id);
        session.commit();
    }
    /*
        通过分类名获得所属的博文
     */
    public List<Article> getArticlesByCategoryName(String name) {
        SqlSession session = MybatisUtil.openSession();
        articleDao = session.getMapper(ArticleDao.class);
        Long categoryId = articleDao.getCategoryIdByName(name);
        List<Article> articles = articleDao.getArticlesByCategoryName(categoryId);
        return articles;
    }
    /*
        通过分类id获取分类；
     */
    public Category getCategoryById(long id){
        SqlSession session = MybatisUtil.openSession();
        articleDao = session.getMapper(ArticleDao.class);
        Category category = articleDao.getCategoryById(id);
        return  category;
    }
}
